/*
 * ClienteDao.java
 *
 * Created on 4 de Junho de 2007, 23:19
 *
 */

package net.sf.jOpinionPoll.dao.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import net.sf.jOpinionPoll.dao.ClienteDao;
import net.sf.jOpinionPoll.dao.ParameterMap;
import net.sf.jOpinionPoll.entity.Cliente;

/**
 *
 * @author erico
 */
public class ClienteDaoJpa extends DaoJpa implements ClienteDao {
    
	/** Creates a new instance of ClienteDao */
    public ClienteDaoJpa() {
    }
    
    private DaoJpaHelper<Cliente> getDaoJpaHelper() {
    	return new DaoJpaHelper<Cliente>(getEntityManager(), Cliente.class);
    }
    
    @Override
    @SuppressWarnings("unchecked")
    public List<Cliente> list(int firstResult, int maxResults, ParameterMap paramMap) {
    	EntityManager em = getEntityManager();
    	DaoJpaHelper<Cliente> daoJpaHelper = getDaoJpaHelper();
    	Query query;
    	String sql =
    		"select c from Cliente c join fetch c.endereco e" +
    		" where (lower(c.cpfcnpj) like :cpfcnpj " + (paramMap.isEmptyValue("cpfcnpj") ? "or c.cpfcnpj is null)" : ")") + " and" +
    		"       (lower(c.nome) like :nome " + (paramMap.isEmptyValue("nome") ? "or c.nome is null)" : ")") + " and" + 
    		"       (lower(c.sobrenome) like :sobrenome " + (paramMap.isEmptyValue("sobrenome") ? "or c.sobrenome is null)" : ")");

		query = daoJpaHelper.createQueryHelper(em, sql, paramMap);
        
        if (maxResults > 0)
        	query.setMaxResults(maxResults);
        
        if (firstResult >= 0)
        	query.setFirstResult(firstResult);
        
        return (List<Cliente>)query.getResultList();
    }
    
	public Cliente findByPk(Object primaryKey) {
		return getDaoJpaHelper().findByPk(primaryKey);
    }
    
	public void add(Cliente newInstance) {
		getDaoJpaHelper().add(newInstance);
    }
    
    public void set(Cliente cliente) {
    	getDaoJpaHelper().set(cliente);
    }
    
    public void remove(Cliente cliente) {
    	getDaoJpaHelper().remove(cliente);
    }
    
    public int count() {
        return getDaoJpaHelper().count();
    }
}